package com.hejian.android.a72ggametools.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.hejian.android.a72ggametools.R;
import com.hejian.android.a72ggametools.adapter.GameCommentAdapter;
import com.hejian.android.a72ggametools.adapter.GameInfoAdapter;
import com.hejian.android.a72ggametools.adapter.HandGiftAdapter;
import com.hejian.android.a72ggametools.bean.GameComment;
import com.hejian.android.a72ggametools.bean.GameDetails;
import com.hejian.android.a72ggametools.bean.GameLike;
import com.hejian.android.a72ggametools.bean.GiftInfo;
import com.hejian.android.a72ggametools.bean.MoneyGame;
import com.hejian.android.a72ggametools.common.Constant;
import com.hejian.android.a72ggametools.imageloader.DoubleCache;
import com.hejian.android.a72ggametools.imageloader.ImageCache;
import com.hejian.android.a72ggametools.imageloader.ImageLoader;
import com.hejian.android.a72ggametools.net.HttpUtils;
import com.hejian.android.a72ggametools.service.DownloadService;
import com.hejian.android.a72ggametools.utils.JsonParse;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/1/15.
 */
public class GameDetailActivity extends AppCompatActivity implements View.OnClickListener {
    public static final String ACTION_DOWNLOAD_PROGRESS = "my_download_progress";
    public static final String ACTION_DOWNLOAD_SUCCESS = "my_download_success";
    public static final String ACTION_DOWNLOAD_FAIL = "my_download_fail";
    private int flag;
    private MyReceiver receiver;

    private Intent intent;
    private String id;
    private MoneyGame moneyGame;
    private GameDetails gameDetails;
    private ImageCache imageCache = new DoubleCache();
    private ImageLoader imageLoader = ImageLoader.getInstance(GameDetailActivity.this, imageCache);
    private Button backBtn;
    private ImageView gameImgBig;
    private ImageView gameInfoIcon;
    private TextView gameInfoName;
    private RatingBar gameInfoRating;
    private TextView gameInfoOther;
    private String TAG = "hejiandebug";
    private ViewPager gameInfoViewPager;
    private ArrayList<View> viewList;
    private View view1;
    private TextView getUB;
    private TextView gameInformation;
    private LinearLayout gameLike1;
    private LinearLayout gameLike2;
    private LinearLayout gameLike3;
    private LinearLayout gameLike4;
    List<GameLike> gameLikeList;
    private PagerAdapter viewpagerAdapter;
    private View view2;
    private ListView gameInfoListView;
    private HandGiftAdapter gameInfoAdapter;
    private View view3;
    private ListView gameCommentListView;
    private GameCommentAdapter gameCommentAdapter;
    private RadioGroup gameInfoGroup;
    private Button view1DownloadBtn;
    private Button view2DownloadBtn;
    private ImageView shareBtn;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_money_item);

        initView();
        initData();
        setAdapter();
        receiver = new MyReceiver();
        setListener();

    }

    private void setAdapter() {
        setViewPagerAdapter();


    }

    private void setGameInfoListAdapter(List<GiftInfo> gameInfoList) {
        gameInfoAdapter = new HandGiftAdapter(gameInfoList, getApplicationContext());
        gameInfoListView.setAdapter(gameInfoAdapter);
    }

    private void setGameCommentAdapter(List<GameComment> gameCommentList) {
        gameCommentAdapter = new GameCommentAdapter(gameCommentList, getApplicationContext());
        gameCommentListView.setAdapter(gameCommentAdapter);
    }

    private void setViewPagerAdapter() {
        viewpagerAdapter = new GameInfoAdapter(viewList);
        gameInfoViewPager.setAdapter(viewpagerAdapter);
    }


    private void setListener() {
        setImgBigListener();
        setViewPagerListener();
        setBtnListener();
        setBackBtnListener();
        setDownloadListener();
        setShareBtnListner();


    }

    private void setImgBigListener() {
        gameImgBig.setOnClickListener(this);
    }

    private void setShareBtnListner() {
        shareBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String share = gameDetails.getAndroidDL();
                Intent intent = new Intent("android.intent.action.SEND");
                intent.putExtra(Constant.SHARE_SINA_WEIBO_ACTION, share);
                intent.putExtra(Constant.SHARE_TENCENT_MSC_ACTION, share);
                intent.putExtra(Constant.SHARE_TENCENT_MSC_TIME_LINE_ACTION, share);
                intent.putExtra(Constant.SHARE_TENCENT_QQ_ACTION, share);
                startActivity(Intent.createChooser(intent, "分享到"));
            }
        });
    }

    private void setDownloadListener() {
        view1DownloadBtn.setOnClickListener(this);
        view2DownloadBtn.setOnClickListener(this);
    }

    private void setBackBtnListener() {
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void setBtnListener() {
        gameInfoGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.game_info_button:
                        gameInfoViewPager.setCurrentItem(0);
                        break;
                    case R.id.game_gift_button:
                        gameInfoViewPager.setCurrentItem(1);
                        break;
                    case R.id.game_comment_button:
                        gameInfoViewPager.setCurrentItem(2);
                        break;
                }
            }
        });
    }


    private void setCurrentButton(int position) {
        for (int i = 0, len = gameInfoGroup.getChildCount(); i < len; i++) {
            if (i == position) {
                ((RadioButton) gameInfoGroup.getChildAt(i)).setTextColor(Color.WHITE);
            } else {
                ((RadioButton) gameInfoGroup.getChildAt(i)).setTextColor(Color.BLUE);
            }
        }
    }

    private void setViewPagerListener() {
        gameInfoViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                Log.i(TAG, "onPageSelected: ........." + position);
                setCurrentButton(position);
                setCurrentSelected(position);

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void setCurrentSelected(int position) {
        switch (position) {
            case 0:
                gameInfoGroup.check(R.id.game_info_button);
                break;
            case 1:
                gameInfoGroup.check(R.id.game_gift_button);
                break;
            case 2:
                gameInfoGroup.check(R.id.game_comment_button);
                break;
        }
    }


    private void initView() {
        backBtn = (Button) findViewById(R.id.game_detail_back);
        shareBtn = (ImageView) findViewById(R.id.share_btn);
        gameImgBig = (ImageView) findViewById(R.id.game_img_big);
        gameInfoIcon = (ImageView) findViewById(R.id.game_info_icon);
        gameInfoName = (TextView) findViewById(R.id.game_info_name);
        gameInfoRating = (RatingBar) findViewById(R.id.game_info_rating);
        gameInfoOther = (TextView) findViewById(R.id.game_info_other);
        gameInfoGroup = (RadioGroup) findViewById(R.id.game_info_other_group);
        gameInfoGroup.check(R.id.game_info_button);
        ((RadioButton) gameInfoGroup.getChildAt(0)).setTextColor(Color.WHITE);
        gameInfoViewPager = (ViewPager) findViewById(R.id.gameinfo_show_viewpager);
        initViewPager1();
        initViewPager2();
        initViewPager3();

    }


    private void initData() {
        flag = 0;
        intent = getIntent();
        if (intent.getStringExtra("id") != null) {
            id = intent.getStringExtra("id");
        } else {
            moneyGame = (MoneyGame) intent.getSerializableExtra("money_item");
            id = moneyGame.getId();
        }
        loadData();
        loadViewPager();

    }

    private void loadGameLike() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                loadgameLikeData();
            }
        }).start();
    }

    private void loadgameLikeData() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("id", gameDetails.getId());
        map.put("platform", "2");
        String buffer = HttpUtils.doPostRequest(Constant.MONEY_GAME_LIKE, map);
        List<GameLike> list = JsonParse.parseGameLikeJson(buffer);
        Message msg = Message.obtain();
        msg.what = 2;
        msg.obj = list;
        handler.sendMessage(msg);
    }

    private void loadViewPager() {
        viewList = new ArrayList<View>();
        viewList.add(view1);
        viewList.add(view2);
        viewList.add(view3);

    }

    private void initViewPager3() {
        view3 = LayoutInflater.from(this).inflate(R.layout.game_info_viewpager_item3, null);
        gameCommentListView = (ListView) view3.findViewById(R.id.game_comment_listview);
    }

    private void initViewPager2() {
        view2 = LayoutInflater.from(this).inflate(R.layout.game_info_viewpager_item2, null);
        gameInfoListView = (ListView) view2.findViewById(R.id.game_info_listview);
        view2DownloadBtn = (Button) view2.findViewById(R.id.game_info_download);

    }


    private void initViewPager1() {
        view1 = LayoutInflater.from(this).inflate(R.layout.game_info_viewpager_item1, null);
        getUB = (TextView) view1.findViewById(R.id.get_ub);
        gameInformation = (TextView) view1.findViewById(R.id.game_information);
        gameLike1 = (LinearLayout) view1.findViewById(R.id.game_like_01);
        gameLike2 = (LinearLayout) view1.findViewById(R.id.game_like_02);
        gameLike3 = (LinearLayout) view1.findViewById(R.id.game_like_03);
        gameLike4 = (LinearLayout) view1.findViewById(R.id.game_like_04);
        view1DownloadBtn = (Button) view1.findViewById(R.id.game_info_download);
    }

    private void loadGameComment() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                loadGameCommentData();
            }
        }).start();
    }

    private void loadGameCommentData() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("id", gameDetails.getId());
        String buffer = HttpUtils.doPostRequest(Constant.GAME_COMMENT_URL, map);
        List<GameComment> list = JsonParse.parseGameCommentJson(buffer);
        Message msg = Message.obtain();
        msg.what = 4;
        msg.obj = list;
        handler.sendMessage(msg);
    }

    private void loadViewPagerGameInfo() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                loadViewPagerGameInfoData();
            }
        }).start();
    }

    private void loadViewPagerGameInfoData() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("gamename", gameDetails.getName());
        map.put("platform", "2");
        map.put("gifttype", "1");
        String buffer = HttpUtils.doPostRequest(Constant.GIFT_LIST_URL, map);
        List<GiftInfo> list = JsonParse.parseHandGiftJson(buffer);
        Message msg = Message.obtain();
        msg.what = 3;
        msg.obj = list;
        handler.sendMessage(msg);
    }


    private void loadData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                loadGameInfoData();
            }
        }).start();
    }

    private void loadGameInfoData() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("id", id);
        String buffer = HttpUtils.doPostRequest(Constant.MONEY_ITEM_URL, map);
        GameDetails details = JsonParse.parseGameItemJson(buffer);
        Message msg = Message.obtain();
        msg.what = 1;
        msg.obj = details;
        handler.sendMessage(msg);

    }

    private List<GiftInfo> gameInfoList;
    private List<GameComment> gameCommentList;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                gameDetails = (GameDetails) msg.obj;
                setView(gameDetails);
                getUB.setText(gameDetails.getDlBackJifen());
                gameInformation.setText(gameDetails.getGameDesc());
                loadGameLike();
                loadViewPagerGameInfo();
                loadGameComment();
            }
            if (msg.what == 2) {
                gameLikeList = (List<GameLike>) msg.obj;
                setView(gameLikeList.get(0), gameLike1);
                setView(gameLikeList.get(1), gameLike2);
                setView(gameLikeList.get(2), gameLike3);
                setView(gameLikeList.get(3), gameLike4);
            }
            if (msg.what == 3) {
                gameInfoList = (List<GiftInfo>) msg.obj;
                setGameInfoListAdapter(gameInfoList);
            }
            if (msg.what == 4) {
                gameCommentList = (List<GameComment>) msg.obj;
                setGameCommentAdapter(gameCommentList);
            }
        }
    };


    private void setView(GameLike gameLike, LinearLayout gameLikelayout) {
        imageLoader.displayImage(gameLike.getIcon(), (ImageView) gameLikelayout.getChildAt(0));
        ((TextView) gameLikelayout.getChildAt(1)).setText(gameLike.getName());
        ((TextView) gameLikelayout.getChildAt(2)).setText(gameLike.getCount_dl() + "次下载");

    }

    private void setView(GameDetails gameDetails) {
        String snapshot = gameDetails.getSnapshot();
        String[] imgUrl = snapshot.split(",");
        String imgBigUrl = imgUrl[0];
        Log.d(TAG, "setView: " + imgBigUrl);
        imageLoader.displayImage(imgBigUrl, gameImgBig);
        imageLoader.displayImage(gameDetails.getIcon(), gameInfoIcon);
        gameInfoName.setText(gameDetails.getName());
        gameInfoRating.setRating(Float.valueOf(gameDetails.getScore()) / 2);
        gameInfoOther.setText("版本：" + gameDetails.getVersion() + "|" + gameDetails.getSize() + " " + gameDetails.getCountDL() + "人下载");

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.game_info_download:
                flag++;
                doCache();
                break;
            case R.id.game_img_big:
                Intent intent = new Intent(GameDetailActivity.this, GameDetailImgActivity.class);
                intent.putExtra("bigimgurl", gameDetails.getSnapshot());
                startActivity(intent);
                break;
        }
    }

    public void doCache() {
        if (flag != 0) {
            if ((flag % 2) == 1) {
                if (DownloadService.getInstance() != null) {
                    view1DownloadBtn.setText((float)(Math.round(DownloadService.getInstance().getProgress()*10))/10 + "%");
                }
                startDownloadService();
            }
            if ((flag % 2) == 0) {
                pauseDownloadService();
            }
        }
    }

    public void startDownloadService() {
        if (DownloadService.getInstance() != null
                && DownloadService.getInstance().getFlag() != DownloadService.Flag_Init) {
            Toast.makeText(this, "已经在下载", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent it = new Intent(this, DownloadService.class);
        it.putExtra("flag", "start");
        it.putExtra("url", gameDetails.getAndroidDL());
        startService(it);
    }

    public void pauseDownloadService() {
        String flag = null;
        int f = DownloadService.getInstance().getFlag();
        if (DownloadService.getInstance() != null) {
            // 如果当前已经暂停，则恢复
            if (f == DownloadService.Flag_Pause) {
                flag = "resume";
            } else if (f == DownloadService.Flag_Down) {
                flag = "pause";
            } else {
                return;
            }
        }
        Intent it = new Intent(this, DownloadService.class);
        it.putExtra("flag", flag);
        startService(it);
    }

    public void stopDownloadService() {
        Intent it = new Intent(this, DownloadService.class);
        it.putExtra("flag", "stop");
        startService(it);
        view1DownloadBtn.setText("下载");
    }


    public void onBackPressed() {
        if (flag == 0){
            finish();
        } else {
            final int f = DownloadService.getInstance().getFlag();
            //XXX:暂停状态下退出？？？
            if (f == DownloadService.Flag_Down || f == DownloadService.Flag_Pause) {
                new AlertDialog.Builder(this).setTitle("确定退出程序？").setMessage("你有未完成的下载任务")
                        .setNegativeButton("取消下载", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            stopDownloadService();
                            GameDetailActivity.super.onBackPressed();
//                                finish();
                            }
                        })
                        .setPositiveButton("后台下载", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                if (f == DownloadService.Flag_Pause) {
                                    Intent it = new Intent(GameDetailActivity.this, DownloadService.class);
                                    it.putExtra("flag", "resume");
                                    startService(it);
                                }
                                GameDetailActivity.super.onBackPressed();
                            }
                        })
                        .create().show();
                return;
            }
            if (DownloadService.getInstance() != null) DownloadService.getInstance().stopSelf();
            super.onBackPressed();
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_DOWNLOAD_PROGRESS);
        filter.addAction(ACTION_DOWNLOAD_SUCCESS);
        filter.addAction(ACTION_DOWNLOAD_FAIL);
        registerReceiver(receiver, filter);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }

    class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ACTION_DOWNLOAD_PROGRESS)) {
                float pro = intent.getExtras().getFloat("progress");
                pro = (float)(Math.round(pro*10))/10;
                Log.i(TAG,"mButton ------ > "+pro+"%");
                view1DownloadBtn.setText(pro + "%");
            } else if (action.equals(ACTION_DOWNLOAD_SUCCESS)) {
                Toast.makeText(GameDetailActivity.this, "下载成功", Toast.LENGTH_SHORT).show();
            } else if (action.equals(ACTION_DOWNLOAD_FAIL)) {
                Toast.makeText(GameDetailActivity.this, "下载失败", Toast.LENGTH_SHORT).show();
            }
        }

    }
}
